<?php

/**
 * 深圳市丹宏昊天电子商务有限公司
 * Class Multi
 * 新批量单控制器
 * songqingwen 2016/12/08
 * @property multi_model $multi_model
 */
class Multi extends MY_Controller
{

    /**
     * Multi constructor.
     * 构造函数
     */
    function __construct()
    {
        parent::__construct();
        $this->load->model('multi_model');
        $this->lang->load('multi');
    }


    //商家展示面板
    public function index_oldd()
    {
        $gp = gp();
        $searchStr = '/orders/Multi/?'; //拼接字符串
        $keys = '';

        $customer_num = 0;
        //die('cntt:' . $cnt_pages);
        if (isset($gp['customerId'])) {
            $customer_num = trim($gp['customerId']);
        }
        if (isset($gp['searchOrderNum'])) {
            $keys = trim($gp['searchOrderNum']);

            // $searchStr = $searchStr . 'searchOrderNum=' . $keys;
        }

        $users = $this->multi_model->GetUserByRole(''); //获取所有用户
        foreach ($users as $k => $v) {
            $users[$k]['chart'] = strtoupper(GetInitial($v['name']));
        }

        $data['users'] = $users;

        $customerList = $this->common_model->selectCustom('mt_customers' , array('type' => 1));
        $data['customerList'] = $customerList;


        $string_cus_beg = '';
        $string_cus_end = '';
        if (!empty($customer_num)) {
            $string_cus_beg = '';
            " `merchant_num` =  '" . $customer_num . "' and  (";
            $string_cus_end = ' )';
        }
        $string_query = "select mt_multi_products .*,mt_multi_orders . merchant_num as merchant_num from mt_multi_products left join mt_multi_orders on mt_multi_products . order_num = mt_multi_orders . order_num where " . $string_cus_beg . " mt_multi_orders . `order_num` COLLATE utf8_general_ci like '%" . $keys . "%'  or mt_multi_products.waybill_num COLLATE utf8_general_ci  like '%" . $keys . "%' " . $string_cus_end . " ";

        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->multi_model->CntMultiOrdersByMerchant($keys , $customer_num); //条数
        $config['per_page'] = 15;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $page = max(1 , intval($gp['page']));
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $data['show_pages'] = $this->pagination->create_links();
        $num_page = ceil($config['total_rows'] / $config['per_page']);

        $string_limit = sprintf(" limit %s , %s" , $slimit , $config['per_page']);

        $list = $this->db->query($string_query . $string_limit)->result_array();

        print_r($list);
        foreach ($list as $k => $v) {
            $list[$k]['merchantName'] = $this->multi_model->GetMerchantName($v['merchant_num']);


            $orders = array();
            foreach ($orders as $ok => $ov) {
                // $orders[$ok]['point'] = $this->multi_model->GetSourceNameById($ov['service_center']);
            }
            $list[$k]['orders'] = $orders;
        }

        $data['list'] = $list;
        $data['show_params'] = "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$num_page}页";

        $this->load->view('defaults/multi/merchant' , $data);
    }

    //商家展示面板
    public function index()
    {
        $gp = gp();
        $searchStr = '/orders/Multi/?'; //拼接字符串
        $keys = '';

        $customer_num = 0;
        //die('cntt:' . $cnt_pages);
        if (isset($gp['customerId'])) {
            $customer_num = trim($gp['customerId']);
        }
        if (isset($gp['searchOrderNum'])) {
            $keys = trim($gp['searchOrderNum']);

            // $searchStr = $searchStr . 'searchOrderNum=' . $keys;
        }

        $users = $this->multi_model->GetUserByRole(''); //获取所有用户
        foreach ($users as $k => $v) {
            $users[$k]['chart'] = strtoupper(GetInitial($v['name']));
        }
        //print_r($users);die;
        //ArraySort($users,'chart',SORT_ASC,SORT_STRING);
        $data['users'] = $users;

        $customerList = $this->common_model->selectCustom('mt_customers' , array('type' => 1));
        $data['customerList'] = $customerList;
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->multi_model->CntMultiOrdersByMerchant($keys , $customer_num); //条数
        $config['per_page'] = 15;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $page = max(1 , intval($gp['page']));
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $data['show_pages'] = $this->pagination->create_links();
        $num_page = ceil($config['total_rows'] / $config['per_page']);
        $list = $this->multi_model->GelMultiOrdersByMerchant($keys , $slimit , $config['per_page'] , $customer_num);


        foreach ($list as $k => $v) {
            $list[$k]['merchantName'] = $this->multi_model->GetMerchantName($v['merchant_num']);
            $orders = $this->multi_model->CntMultiOrdersByMerNmm($keys , $v['merchant_num']);
            foreach ($orders as $ok => $ov) {
                $orders[$ok]['point'] = $this->multi_model->GetSourceNameById($ov['service_center']);
            }
            $list[$k]['orders'] = $orders;
        }

        $data['list'] = $list;
        $data['show_params'] = "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$num_page}页";

        $this->load->view('defaults/multi/merchant' , $data);
    }

    /**
     * 展示列表
     */
    public function index_bak()
    {
        $gp = gp();
        $searchStr = '/orders/Multi/?'; //拼接字符串
        $keys = '';
        //die('cntt:' . $cnt_pages);
        if (isset($gp['searchOrderNum'])) {
            $keys = trim($gp['searchOrderNum']);
            $searchStr = $searchStr . 'searchOrderNum=' . $keys;
        }
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->multi_model->CntMultiOrders($keys); //条数
        $config['per_page'] = 15;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $page = max(1 , intval($gp['page']));
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $data['show_pages'] = $this->pagination->create_links();
        $num_page = ceil($config['total_rows'] / $config['per_page']);
        $list = $this->multi_model->GelMultiOrders($keys , $slimit , $config['per_page']);
        foreach ($list as $k => $v) {
            $list[$k]['point'] = $this->multi_model->GetSourceNameById($v['source_site']);
            $list[$k]['merchantName'] = $this->multi_model->GetMerchantName($v['merchant_num']);
        }
        $data['list'] = $list;
        $data['show_params'] = "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$num_page}页";

        $this->load->view('defaults/multi/orders' , $data);
    }

    public function test()
    {
        $this->load->view('defaults/multi/waybill');
    }

    /**
     * ajax添加来货单的展示
     */
    public function ajaxAddWaybill()
    {
        $gp = gp();


        $qty_arr = explode(',' , $gp['qty']);
        $sku_arr = explode(',' , $gp['sku']);
        $imei_arr = explode('^' , $gp['imeis']);
        $imeis = trim($gp['imeis']);
        $order_num = empty($gp['orderNum']) ? '' : trim($gp['orderNum']);
        $waybill_num = empty($gp['num']) ? '' : trim($gp['num']);
        $quantity = array_sum($qty_arr);
        $add_time = time();

        //插入来货单
        $data = array('waybill_num' => $waybill_num , //货运单号码
            'order_num' => $order_num , //维修单号
            'quantity' => $quantity , //来货数量
            'status' => 1 , //来货单状态，默认为1，预留，暂时没有意义
            'add_time' => $add_time , //来货时间
            'add_user' => serialize($this->users) , //操作员资料
            'remark' => empty($gp['remark']) ? '' : trim($gp['remark']) , 'unpk_cnt' => 1);

        $result = $this->multi_model->AddWaybill($data);
        $arr_products = array();
        $count = 0;
        for ($i = 0 ; $i < count($qty_arr) ; $i++) {

            for ($ii = 0 ; $ii < $qty_arr[$i] ; $ii++) {

                $arr_products[$count]['order_num'] = $order_num;
                $arr_products[$count]['waybill_num'] = $waybill_num;
                $arr_products[$count]['sku'] = $sku_arr[$i];
                //重组imei
                $arr_code = explode(',' , $imei_arr[$i]);
                if (count($arr_code) > 0) {
                    $arr_products[$count]['imei'] = $arr_code[$ii];
                }
                $arr_products[$count]['status'] = '1';
                $count++;
            }

        }

        $this->multi_model->AddMultiProducts4WaybillV2($arr_products , $arr_count , $order_num);

        $this->multi_model->SetActualQuantity($order_num , $quantity);
        $waybill_had_products = $this->multi_model->getMultiProductsByWaybillNum($waybill_num); //获取来货单下所有的产品id
        $arr_unpackage = array('unpackage_num' => $waybill_num . '_1' , //拆包单号,varchar
            'order_num' => $order_num , //维修单id，int
            'waybill_num' => $waybill_num , //来货单id，int
            'source_id' => 0 , //来源id，默认为0 ，实际数值为所拆包的id，本表的id，int
            'add_time' => $add_time , //添加时间
            'add_user' => serialize($this->users) , //所属的所有产品id,text
            'product_ids' => $waybill_had_products//所属的所有产品id,text
        );

        $this->multi_model->AddUnpackage($arr_unpackage);

        die($result);
    }

    /**
     * ajax拆包处理函数
     */
    public function ajaxAddUnpackage()
    {
        $gp = gp();
        $orderNum = empty($gp['orderNum']) ? '' : trim($gp['orderNum']);
        $unId = empty($gp['uid']) ? '' : trim($gp['uid']); //
        $wbNum = empty($gp['num']) ? '' : trim($gp['num']);
        $unCnt = empty($gp['uncnt']) ? 0 : trim($gp['uncnt']); //拆包数量
        $reCnt = empty($gp['recnt']) ? 0 : trim($gp['recnt']); //剩余数量
        $sort = empty($gp['sort']) ? 0 : trim($gp['sort']); //当前排序
        $unpknum = empty($gp['unpkNum']) ? '' : trim($gp['unpkNum']);
        $this->multi_model->DoUnpackage($unCnt , $reCnt , $orderNum , $wbNum , $unId , $sort , $unpknum);
        echo('1');
        exit;
    }

    /**
     * 根据维修单ID，获取来货单集合
     */
    public function ajaxGetWaybillByOrderNum()
    {
        $gp = gp();
        $result = $this->multi_model->GetWaybillBybNum($gp['orderNum']);
        foreach ($result as $k => $v) {
            $result[$k]['add_time'] = date("Y-m-d m:i:s" , $v['add_time']);
        }
        echo json_encode($result);
        exit;
    }

    /**
     * ajax合并包裹
     */
    public function ajaxMergePackage()
    {
        $gp = gp();
        $num = $gp['num'];
        $order_num = $gp['order_num'];
        $unpk_ids = $gp['unpk_ids'];
        $unpk_nums = $gp['unpk_nums'];
        $tec_id = $gp['userid'];
        $status = 0;
        $site_id = 0;
        $result = $this->multi_model->DoMergePackage($num , $order_num , $unpk_ids , $unpk_nums , $status , $site_id , $tec_id);
        exit;
    }

    /**
     * 合并大订单
     */
    public function ajaxMergePackageByOrders()
    {
        $gp = gp();

        $order_num = $gp['order_num'];
        $arr = explode(',' , rtrim($order_num , ','));
        foreach ($arr as $k => $v) {
            $arr[$k] = '\'' . $v . '\'';
        }
        $order_num = implode($arr , ',');

        $result = $this->multi_model->DoMergePackageByOrders($order_num);
        echo($result);
        exit;
    }

    //批量单合并包裹
    public function merge()
    {
        $gp = gp();
        $searchStr = '/orders/Multi/merge/?'; //拼接字符串
        $keys = '';
        //die('cntt:' . $cnt_pages);
        if (isset($gp['searchOrderNum'])) {
            $keys = trim($gp['searchOrderNum']);

            $searchStr = $searchStr . 'searchOrderNum=' . $keys;
        }

        $users = $this->multi_model->GetUserByRole(''); //获取所有用户
        foreach ($users as $k => $v) {
            $users[$k]['chart'] = strtoupper(GetInitial($v['name']));
        }


        //print_r($users);die;
        //ArraySort($users,'chart',SORT_ASC,SORT_STRING);
        $data['users'] = $users;
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $config['total_rows'] = $this->multi_model->CntMultiPks($keys); //条数
        $config['per_page'] = 15;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $page = max(1 , intval($gp['page']));
        $slimit = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $data['show_pages'] = $this->pagination->create_links();
        $num_page = ceil($config['total_rows'] / $config['per_page']);
        $list = $this->multi_model->GelMultiPks($keys , $slimit , $config['per_page']);

        foreach ($list as $k => $v) {
            $list[$k]['pids'] = $this->multi_model->ProductsByPkNum($v['num']);
            $list[$k]['nofinish'] = $this->multi_model->CntIsFinish($v['num']);
            $tmp_tec = $this->multi_model->GetTecById($v['tec_id']);
            $list[$k]['tec'] = $tmp_tec['name'];
            $list[$k]['cnt_ship'] = $this->multi_model->CntWaitDForDelivery($v['num']); //未发货数量
        }
        $data['list'] = $list;
        $data['show_params'] = "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$num_page}页";

        $this->load->view('defaults/multi/merge_list' , $data);
    }

    public function ajaxGetProductsBypkId()
    {
        $gp = gp();
        $pkid = $gp['pkid'];
        $result = $this->multi_model->GetProductsByPkid($pkid);
        echo json_encode($result);
        exit;
    }

    public function ajaxSaveMerge()
    {
        $gp = gp();

        $str = $gp['str'];
        $arr = explode('&' , $str);
        $arr_2 = array();
        $iii = 0;
        for ($ii = 0 ; $ii < count($arr) ; $ii++) {
            $a = explode('=' , $arr[$ii]);
            $arr_2[$iii][$a[0]] = str_ireplace('null' , '' , urldecode($a[1]));
            if ((($ii + 1) % 20) == 0) {
                $iii++;
            }
        }
        //print_r($arr_2);die;
        $res = $this->multi_model->SetMerge($arr_2);
    }

    /**
     *
     *
     */
    public function ajaxSaveMergeTime()
    {
        $gp = gp();
        $et = $gp['et'];
        $num = $gp['num'];
        $this->db->query(sprintf("update `mt_multi_mergepackage` set `end_time` = '%s' where `num` = '%s'" , $et , $num));
    }

    /**
     * ajax处理产品状态
     */
    public function ajaxSetIsFinnish()
    {
        $gp = gp();
        $id = $gp['id'];
        $st = $gp['status'];
        $res = $this->multi_model->SetProIsFinnish($id , $st);
    }

    /**
     * ajax查询单号是否重复
     */
    public function ajaxCheckNum()
    {
        $gp = gp();
        $num_type = trim($gp['nt']);
        $num = trim($gp['n']);
        $res = $this->multi_model->CheckNum($num_type , $num);
        echo json_encode($res);
        exit;
    }

    /**
     * @param $query
     * @return array
     * 拆分参数
     */
    function convertUrlQuery($query)
    {
        $queryParts = explode('&' , $query);
        $params = array();
        $return = array();

        foreach ($queryParts as $param) {
            $item = explode('=' , $param);
            $params[$item[0]] = $item[1];
        }
        return $return;
    }

    public function DoExportTemp()
    {
        $gp = gp();
        if (empty($gp['pkNum'])) {
            return;
        }
        $sql = sprintf("select * from `mt_multi_products` where `pk_num` = '%s'" , $gp['pkNum']);
        $res = $this->db->query($sql)->result_array();
        //print_r($res);die;
        date_default_timezone_set('Asia/Shanghai');
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment; filename=" . $gp['pkNum'] . "-" . date('Ymd_His' , time()) . ".xls");


        $str = "<table border='1'><tr>" . "<th></th>" . "<th colspan='5' style='background-color:red;text-align:center;'>拆包质检</th>" . "<th colspan='4' style='background-color:orange;text-align:center;'>维修师</th>" . "<th colspan='5' style='background-color:yellow;text-align:center;'>出库质检</th>" . "<th></th>" . "<th></th>" . "</tr><tr>" . "<td>PID</td>" . "<td>产品状态</td>" . "<td>质保类型</td>" . "<td>外观状况</td>" . "<td>随机附件</td>" . "<td>故障编号</td>" . "<td>产品状态</td>" . "<td>是否质保</td>" . "<td>维修项</td>" . "<td>添加配件</td>" . "<td>合格状态</td>" . "<td>描述状况</td>" . "<td>外观状况</td>" . "<td>随机附件</td>" . "<td>故障编号</td>" . "<td>备注</td>" . "<td>物料号</td>" . "</tr>";
        echo($str);
        foreach ($res as $k => $v) {
            $tt = " <tr>" . "<td>" . $v['id'] . "</td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "</tr>";
            echo $tt;
        }
        echo '</table>';
        exit;
    }

    public function DoExportTemp2()
    {
        $gp = gp();
        if (empty($gp['pkNum'])) {
            return;
        }
        $sql = sprintf("select * from `mt_multi_products` where `pk_num` = '%s'" , $gp['pkNum']);
        $res = $this->db->query($sql)->result_array();
        //print_r($res);die;
        date_default_timezone_set('Asia/Shanghai');
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment; filename=" . $gp['pkNum'] . "-" . date('Ymd_His' , time()) . ".xlsx");
        echo '' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '拆包质检' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '维修师' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '' . chr(9);
        echo '出库质检' . chr(9);
        echo '' . chr(9);
        echo '' . chr(13);
        echo 'PID' . chr(9);
        echo '包裹单号' . chr(9);
        echo '产品状态' . chr(9);
        echo '质保类型' . chr(9);
        echo '外观状况' . chr(9);
        echo '随机附件' . chr(9);
        echo '故障编号' . chr(9);
        echo '备注' . chr(9);
        echo '产品状态' . chr(9);
        echo '是否质保' . chr(9);
        echo '维修项' . chr(9);
        echo '添加配件' . chr(9);
        echo '备注' . chr(9);

        echo '合格状态' . chr(9);
        echo '描述状况' . chr(9);
        echo '外观状况' . chr(9);
        echo '随机附件' . chr(9);
        echo '故障编号' . chr(9);
        echo '备注' . chr(9);
        echo chr(13);
        foreach ($res as $k => $v) {
            echo $v['id'] . chr(9);
            echo $v['pk_num'] . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo '' . chr(9);
            echo chr(13);
        }
        exit;
    }

    /**
     * ajax设置维修包裹的维修师
     */
    public function ajaxSetTecId()
    {
        $gp = gp();
        $tecId = trim($gp['tecid']);
        $num = trim($gp['num']);
        $res = $this->multi_model->SetTecId($tecId , $num);
        echo json_encode($res);
        exit;
    }

    /**
     * ajax根据包裹号返回所属产品的imei
     */
    public function ajaxGetImeisByPkNum()
    {
        $v = gp();
        $arr_imeis = $this->multi_model->GetImeiByPkNum($v['num']);
        echo json_encode($arr_imeis);
        exit;
    }

    /**
     * 根据包裹号获取可以打包的产品id
     */
    public function ajaxGetShippingProductsId()
    {
        $v = gp();
        $pkNums = $v['pknum'];
        $arr_nums = explode(',' , $pkNums);
        foreach ($arr_nums as $k => $vv) {
            if (!empty($vv)) {
                $arr_nums[$k] = "'" . $vv . "'";
            }
        }
        $pkNums = implode(',' , $arr_nums);

        $pids = $this->multi_model->GetShippingProducts($pkNums);
        $str = '';
        for ($ii = 0 ; $ii < count($pids) ; $ii++) {
            $str .= ' <input type="checkbox" value="' . $pids[$ii] . '" name="shipping_product" id="shipping_pro_' . $pids[$ii] . '"><label for="shipping_pro_' . $pids[$ii] . '">' . $pids[$ii] . '</label>';
        }
        echo($str);
        exit;
    }

    /**
     * 添加物流单号
     */
    public function ajaxDoShipping()
    {
        $gp = gp();
        $pkNums = $gp['pknum'];
        $arr_nums = explode(',' , $pkNums);
        foreach ($arr_nums as $k => $vv) {
            if (!empty($vv)) {
                $arr_nums[$k] = "'" . $vv . "'";
            }
        }
        $pkNums = implode(',' , $arr_nums);
        $shipNums = $gp['ship_num'];
        $res = $this->multi_model->DoShippingProducts($pkNums , $shipNums);
        echo json_encode($res);
        exit;
    }

    /**
     * @return string
     * 返回打印店状态
     */
    public function ajaxPrintWaybill()
    {
        return '1';
    }

    public function ajaxGetBarcode()
    {
        $gp = gp();
        $waybill_num = $gp['num'];
        $order_num = $gp['orderNum'];
        $type = "C128"; //$gp['tc'];
        $w = '2';
        $h = '15';
        $this->load->library('barcode');
        $p = $this->multi_model->GetPidByWaybillNum($waybill_num);
        $str = '';
        $c = $this->db->query(sprintf("select name_en from mt_multi_orders  inner JOIN mt_customers on mt_multi_orders.merchant_num =  mt_customers.id where order_num  = '%s'" , $order_num))->row_array();
        foreach ($p as $k => $v) {
            $str .= '<div style="width:49mm;height:29.9mm;overflow: hidden;margin:0 auto;margin-top:0;"> ' . '<table style="font-family:Arial;font-size:7px;line-height:15px;color:#000">' . '<tr></tr>' . '<tr><td style="padding: 0;text-align:center;">&nbsp;DN:' . $waybill_num . '</td></tr>' . '<tr><td  style="padding:0; padding-top:1px;text-align:center;"><img src="data:image/png;base64,' . $this->barcode->getBarcodePNG($v['id'] , $type , $w , $h) . '" style="text-align:center;"/></td></tr>' . '<tr><td align="center" style="padding: 0; padding-bottom:2px;"><strong style="font-size:19px">' . $v['order_num'] . '</strong></td></tr><tr><td style="padding: 0;">' . mb_substr($c['name_en'] , 0 , 20 , "utf-8") . '</td></tr>' . '<tr><td><strong style="font-size:19px">' . $v['product_brand'] . ' </strong>/ <strong style="font-size:19px">' . $v['product_model'] . '</strong> </td><tr><td>sku:' . $v['sku'] . ' / <font>pid:</font><strong style="font-size:15px">' . $v['id'] . '</strong></td></tr>' . '<tr><td>SN:' . $v['imei'] . '</td></tr>' . '</table></div>';
        }
        die($str);
    }

    public function ajaxLoadOrderInfoByOrderNum()
    {
        $gp = gp();
        $res = $this->common_model->selectCustom('mt_multi_orders' , array('order_num' => $gp['on']));
        foreach ($res as $k => $v) {
            $res[$k]['products'] = $this->common_model->selectCustom('mt_multi_products' , array('order_num' => $v['order_num']));
        }
        echo(json_encode($res));
        exit;
    }

    /**
     * 加载订单所含产品详情
     */
    public function ajaxLoadProductsByOrderNum()
    {
        $gp = gp();
        $page = intval($gp['page']);
        $rows = intval($gp['rows']);
        //计算总条数
        $sql_total = "select count(`id`) as cnt from `mt_multi_products` where  `order_num` = '" . $gp['on'] . "'";
        $res_total = $this->db->query($sql_total)->row_array();
        $total = intval($res_total['cnt']);
        $sql = "select * from `mt_multi_products` where `order_num` = '" . $gp['on'] . "' order by `id` desc ";
        if ($page > 0 && $rows > 0) {
            $start = (($page - 1) * $rows);
            $sql = $sql . ' limit ' . $start . ' , ' . $rows;
        }

        $res = $this->db->query($sql)->result_array();
        foreach ($res as $k => $v) {
            $cat = $this->db->query("select `name_ch`,`name_en` from `mt_product_category` where `id`='" . $v['category_id'] . "' ")->row_array();
            $res[$k]['cat_name'] = $cat['name_' . $this->curLang];
        }
        echo(json_encode(array('total' => $total , 'rows' => $res)));
        exit;
    }

    /**
     * 加载订单地址信息
     */
    public function ajaxLoadOrderAddress()
    {
        $gp = gp();
        $sql = sprintf("select * from `mt_multi_orders` where `order_num` = '" . trim($gp['on']) . "'");
        $res = $this->db->query($sql)->row_array();
        echo(json_encode(array('addr' => ($res['delivery_country'] . ' ' . $res['delivery_city'] . ' ' . $res['delivery_state'] . ' ' . $res['delivery_street_address'] . ' ' . $res['delivery_zipcode']) , 'customer' => ($res['consumer_name'] . ' ' . $res['consumer_phone'] . ' ' . $res['consumer_address']))));
        exit;
    }

    public function ajaxGetSkusByOrderNum()
    {
        $gp = gp();
        $sql = sprintf("select `sku` from `mt_multi_products` where `order_num` = '" . trim($gp['on']) . "' group by `sku`");
        $res = $this->db->query($sql)->result_array();
        echo(json_encode($res));
        exit;
    }

    public function ajaxGetWaybill()
    {

        $gp = gp();
        $sql = sprintf("select `sku`,product_model,product_brand from `mt_multi_products` where `order_num` = '" . trim($gp['on']) . "' and `waybill_num`='' group by `sku` ");
        $res = $this->db->query($sql)->result_array();

        $str = '';
        foreach ($res as $k => $v) {
            $str .= '<tr class="tttr_ttr">
                <td style="vertical-align: top;width:160px;">
                model:' . $v['product_model'] . '<br>
                    brand:' . $v['product_brand'] . '<br>
                    sku:' . $v['sku'] . '
                </td>
                <td style="vertical-align: top;width:80px;">
                    <input style="height:25px;line-height:25px;" type="text" class="layui-input cl_ship_quantity" placeholder="Quantity"
                           name="txtShipQuantity" dt-sku="' . $v['sku'] . '">
                </td>
                <td>
                    <textarea class="layui-textarea cl_imeis"  name="txtShipImeiNums" style="min-height:50px"
                              placeholder="请用扫描枪或者英文逗号分隔"></textarea>
                </td>
            </tr>';
        }
        header("Content-type: text/html; charset=utf-8");
        echo($str);
        exit;
    }

    /**
     * ajax加载随机附件
     */
    public function ajaxLoadAcc()
    {
        $gp = gp();
        $sql = sprintf("select * from  mt_product_accessory where category = '" . trim($gp['catid']) . "'");
        $res = $this->db->query($sql)->result_array();
        $str = '';

        foreach ($res as $k => $v) {
            $str .= ' <input type="checkbox" value="' . $v['id'] . '" name="inp_unpkqc_accessories" id="iuacc_' . $v['id'] . '"><label for="iuacc_' . $v['id'] . '">' . $v['name_' . $this->curLang] . '</label>';
        }
        header("Content-type: text/html; charset=utf-8");
        echo($str);
        exit;
    }

    /**
     * ajax加载随机附件
     */
    public function ajaxLoadFault()
    {
        $gp = gp();
        $sql = sprintf("select * from  mt_product_fault where category = '" . trim($gp['catid']) . "'");
        $res = $this->db->query($sql)->result_array();
        $str = '';

        foreach ($res as $k => $v) {
            $str .= ' <li><li><input type="checkbox" value="' . $v['id'] . '" name="inp_unpkqc_fault" id="iufault_' . $v['id'] . '"><label for="iufault_' . $v['id'] . '">' . $v['name_' . $this->curLang] . '</label></li>';
        }
        header("Content-type: text/html; charset=utf-8");
        echo($str);
        exit;
    }

    public function ajaxLoadItem()
    {
        $gp = gp();
        $sql = sprintf("select * from  `mt_product_repair_item` where category = '" . trim($gp['catid']) . "'");
        $res = $this->db->query($sql)->result_array();
        $str = '';

        foreach ($res as $k => $v) {
            $str .= ' <li><input type="checkbox" value="' . $v['id'] . '" name="inp_repair_item" id="iuitem_' . $v['id'] . '"><label for="iuitem_' . $v['id'] . '">' . $v['name_' . $this->curLang] . '</label></li>';
        }
        header("Content-type: text/html; charset=utf-8");
        echo($str);
        exit;
    }


    public function DoExportOrders()
    {

        if (empty($_GET['orderNum'])) {
            return;
        }
        $order_num = $_GET['orderNum'];
        $order_info = $this->common_model->selectFirst('mt_multi_orders' , array('order_num' => $order_num));
        $str_order = '<tr><td colspan="3">OrderNum:' . $order_info['order_num'] . '</td><td colspan="3">下单数量：' . $order_info['quantity'] . '</td><td colspan="3">到货数量：' . $order_info['actual_quantity'] . '</td><td colspan="3">下单日期:' . date('Y-m-d' , $order_info['add_time']) . '</td><td  colspan="3"></td></tr>';


        $waybill_info = $this->common_model->selectCustom('mt_multi_waybill' , array('order_num' => $order_num));
        $str_waybill = '';
        foreach ($waybill_info as $k => $v) {
            $str_waybill .= '<tr><td>来货单号：' . $v['waybill_num'] . '</td><td>到货日期：' . date('Y-m-d' , $v['add_time']) . '</td><td>到货数量：' . $v['quantity'] . '</td><td>PID</td><td>SKU</td><td>Model</td><td>SN.</td><td>外观状况</td><td>随机附件</td><td>故障项</td><td>维修项</td><td>所需配件</td><td>出库备注</td></tr>';


            $product_info = $this->multi_model->GetProductsByWaybillNum($v['waybill_num']);

            foreach ($product_info as $kp => $vp) {
                $str_waybill .= '<tr><td colspan="3"></td><td>' . $vp['id'] . '</td><td>' . $vp['product_sku'] . '</td><td>' . $vp['product_model'] . '</td><td>' . $vp['imei'] . '</td><td>' . $vp['unpkqc_exterior'] . '</td><td>' . $vp['unpkqc_accessories'] . '</td><td>' . $vp['unpkqc_fault'] . '</td><td>' . $vp['repair_repair_item'] . '</td><td>' . $vp['repair_accessories'] . '</td><td>' . $vp['qc_remark'] . '</td></tr>';
            }
        }


        $sql = sprintf("select * from `mt_multi_products` where `order_num` = '%s' order by `id` desc " , $order_num);
        $res = $this->db->query($sql)->result_array();
        //print_r($res);die;
        date_default_timezone_set('Asia/Shanghai');
        header("Content-Type:text/html;charset=utf-8");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment; filename=" . $order_num . "-" . date('Ymd_His' , time()) . ".xls");
        echo("<table border='1'>" . $str_order . $str_waybill . "</table>");

//        $str = "<table border='1'>" . $str_order . "<tr>" . "<th></th>" . "<th colspan='5' style='background-color:red;text-align:center;'>拆包质检</th>" . "<th colspan='4' style='background-color:orange;text-align:center;'>维修师</th>" . "<th colspan='5' style='background-color:yellow;text-align:center;'>出库质检</th>" . "<th></th>" . "<th></th>" . "</tr><tr>" . "<td>PID</td>" . "<td>产品状态</td>" . "<td>质保类型</td>" . "<td>外观状况</td>" . "<td>随机附件</td>" . "<td>故障编号</td>" . "<td>产品状态</td>" . "<td>是否质保</td>" . "<td>维修项</td>" . "<td>添加配件</td>" . "<td>合格状态</td>" . "<td>描述状况</td>" . "<td>外观状况</td>" . "<td>随机附件</td>" . "<td>故障编号</td>" . "<td>备注</td>" . "<td>物料号</td>" . "</tr>";
//        echo($str);
//        foreach ($res as $k => $v) {
//            $tt = " <tr>" . "<td>" . $v['id'] . "</td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "<td></td>" . "</tr>";
//            echo $tt;
//        }
//        echo '</table>';

        exit;
    }


    public function ajaxGetShippoingNum()
    {
        $gp = gp();
        $pknum = trim($gp['num']);
        $sql = sprintf("select id,order_num,shipping_num,shipping_time from mt_multi_products where pk_num = '%s' and `shipping_num` is not null order by `shipping_time` desc" , $pknum);
        $res = $this->db->query($sql)->result_array();
        foreach ($res as $k => $v) {
            $res[$k]['shipping_time'] = date('Y-m-d' , $v['shipping_time']);
        }

        echo(json_encode($res));
        exit;
    }

    public function ajaxGetShippoingNums()
    {
        $gp = gp();
        $pknum = trim($gp['num']);

        $sql = sprintf("select id,order_num,shipping_num,shipping_time from mt_multi_products where pk_num in (%s) and `shipping_num` is not null order by `shipping_time` desc" , $pknum);
      
        $res = $this->db->query($sql)->result_array();
        foreach ($res as $k => $v) {
            $res[$k]['shipping_time'] = date('Y-m-d' , $v['shipping_time']);
        }

        echo(json_encode($res));
        exit;
    }

    /**
     * 推送订单到SF
     * @param string $id
     */
    function pushSF($id = '')
    {
        $this->load->model('oms_to_sf001_multiorder' , 'sfModel');
        $result = $this->sfModel->oms_to_sf001_multiorder($id);
        if ($result['status']) {
            $this->common_model->update('mt_multi_orders' , array('isSync_sf' => 1) , array('id' => $id));
        }
        if (is_array($result)) {
            gsh_output($result);
        }
        else {
            echo $result;
        }
    }


}
